package com.sneakxy.cloudbase.platform.service;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import com.sneakxy.cloudbase.platform.bean.Setting;
import com.sneakxy.cloudbase.platform.repository.SettingRepository;
import com.sneakxy.mybatis.commons.repository.query.domain.CriteriaBuilder;

/**
 * 个人设置信息业务接口实现
 * @author 潜行的青衣
 * @see
 */
@Service
public class SettingService extends BaseService<Setting, String, SettingRepository> implements ISettingService {

	@Value("${merge.size.account}")
	private int mergeSize;
	
	@Override
	public String getTableName(String owner) {
		return getTableName(owner, mergeSize);
	}

	@Override
	public int deleteByKey(String owner, String key) {
		String tableName = getTableName(owner);
		return getRepository().deleteByKey(owner, key, tableName);
	}

	@Override
	public void save(String owner, String key, String value) {
		String tableName = getTableName(owner);
		Setting setting = findSetting(owner, key);
		if(setting == null) {
			setting = new Setting();
		}
		setting.setKey(key);
		setting.setValue(value);
		setting.setOwner(owner);
		save(setting, tableName);
	}

	public Setting findSetting(String owner, String key) {
		String tableName = getTableName(owner);
		CriteriaBuilder<Setting> builder = new CriteriaBuilder<>(Setting.class);
		builder.andEq("owner", owner);
		builder.andEq("key", key);
		return findOne(builder.build(), tableName);
	}
	
	@Override
	public String findValueByKey(String owner, String key) {
		Setting setting = findSetting(owner, key);
		return setting != null ? setting.getValue() : null;
	}

	@Override
	public Map<String, String> findSettings(String owner) {
		String tableName = getTableName(owner);
		CriteriaBuilder<Setting> builder = new CriteriaBuilder<>(Setting.class);
		builder.andEq("owner", owner);
		List<Setting> settings = getRepository().findAll(builder.build(), tableName, Sort.by("key"));
		Map<String, String> result = new LinkedHashMap<>();
		for(Setting setting: settings) {
			result.put(setting.getKey(), setting.getValue());
		}
		return result;
	}

}
